package com.weactivity.controller;

import com.weactivity.dto.Result;
import com.weactivity.service.FileUploadService;
import com.weactivity.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
public class FileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

    /**
     *
     * 给前端返回一个URL 用户可以通过该URL点击下载活动资料
     * @param file
     * @return
     * @throws Exception
     */

    @PostMapping("file")
    public Result upload(@RequestParam("aid") int aid, @RequestParam("file") MultipartFile file) throws Exception{
        //源文件名称
        String originalFileName =file.getOriginalFilename();
        //给源文件命名，记得需要获取文件名后缀
        String fileName = UUID.randomUUID().toString()+originalFileName.substring(originalFileName.lastIndexOf("."));
        //使用本地存储方式
        //file.transferTo(new File("C:\\Users\\ASUS\\Desktop\\file\\" + filename));

        //使用阿里云OSS服务，具体见AliOssUtil类
        String url = AliOssUtil.uploadFile(fileName, file.getInputStream());
        int count = fileUploadService.insert(aid,url);
        if (0 == count){
            System.out.println("资料上传失败，稍后在试");
        }
        return Result.ok(url);

    }

    /**
     * 展示所有活动资料
     * @param aid
     * @return
     */
    @GetMapping("/show")
    public Result show(@RequestParam("aid") int aid){

        List<String> urlList =  fileUploadService.showAll(aid);

        return Result.ok(urlList);
    }

    @PostMapping("/del")
    public Result deleteByUrl(@RequestParam("aid") int aid ,@RequestParam("url") String url){

      int count =  fileUploadService.deleteByUrl(aid,url);
      if (0 == count){
          return Result.fail("删除失败");
      }
      return Result.ok();

    }

}
